<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.searchBtn"
      >
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">产品名称：{{ info.commonName }}</div>
              <div class="lable">生产批号：{{ info.batchNumber }}</div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-input
                  v-model="filterInfo.keyword"
                  :clearable="true"
                  placeholder="请输入个体码"
                  @keyup.enter.native="search"
                  @input="(e) => (filterInfo.keyword = validSe(e))"
                >
                </el-input>
                <el-button style="margin-left: 10px" @click="search"
                  >搜索</el-button
                >
              </div>
            </div>
          </div>
        </template>
      </NewPageFilter>
    </div>

    <dialog-table
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :check-box="false"
      :pager="false"
      :tab-index="true"
      :handle="tableInfo.handle"
      :listen-height="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      @handleEvent="handleEvent"
    >
    </dialog-table>
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
    <page-dialog
      :title="revokeDialogInfo.title"
      v-model:visible="revokeDialogInfo.revokeVisible"
      :width="revokeDialogInfo.width"
      :bt-loading="revokeDialogInfo.btLoading"
      :bt-list="revokeDialogInfo.btList"
    >
      <page-form
        class="paddingBox order-model-formBox flex_wrap_start_start"
        :data="formInfo.data"
        :field-list="formInfo.fieldList"
        :label-width="formInfo.labelWidth"
        style="width: 100%"
      >
        <template v-slot:form-invalidQty>
          <div
            v-if="formInfo.data.codeType === 1 || formInfo.data.codeType === 4"
          >
            <el-input-number
              v-model.lazy="formInfo.data.largeUnitQty"
              clearable
              style="width: 100%"
              controls-position="right"
              :precision="
                formInfo.data.qtyOperateMode === 0 ||
                formInfo.data.qtyOperateMode === 2
                  ? 0
                  : systemConfig.qty_show_precision
              "
              @change="changeLarge($event, formInfo.data)"
              :min="0"
              :max="largeMax(formInfo.data)"
            />
            <span style="padding-left: 10px; position: absolute">{{
              formInfo.data.unitName
            }}</span>

            <div
              v-if="
                formInfo.data.unitConvertCoefficient > 1 &&
                formInfo.data.qtyOperateMode === 2
              "
            >
              <el-input-number
                style="width: 100%; margintop: 18px"
                v-model.lazy="formInfo.data.smallUnitQty"
                clearable
                controls-position="right"
                :precision="0"
                :min="0"
                :max="smallMax(formInfo.data)"
              />
              <span style="padding-left: 10px; position: absolute">{{
                formInfo.data.calcUnitName
              }}</span>
            </div>
          </div>
          <span
            v-else-if="
              formInfo.data.codeType === 2 || formInfo.data.codeType === 3
            "
            >{{ $fn.qtyFormatter(formInfo.data.qty) }}</span
          >
        </template>
      </page-form>
    </page-dialog>
  </page-dialog>
</template>

<script setup name="IndividualDetails">
import PageDialog from '@/components/PageDialog/index'

import chosePrinter from '@/components/ChosePrinter/index'
import {
  getWithTableRecordOrderDetailAll,
  withTableRecordOrderDetailPrintQrCodeVO,
  withTableRecordOrderRevokeDetail,
} from '@/api/withTable'
import { getCustomizeSetting } from '@/api/customize'
import DialogTable from '@/components/DialogTable/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  api: {
    type: Function,
    default: getWithTableRecordOrderDetailAll,
  },
  showDialog: {
    type: Boolean,
  },
  pageStatus: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
})

// 过滤相关配置
const filterInfo = reactive({
  keyword: '',
  query: {
    queryMap: {
      ...props.query,
    },
    queryParams: {},
    customizeUserVO: {},
  },
  searchBtn: [{ slot: true, value: 'button' }],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  copyData: [],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '打印二维码',
        event: printSingleQrCode,
        show: true,
        ifRender: ifRenderValue,
      },
      {
        label: '无痕撤回',
        event: noTraceRevoke,
        show: proxy.$permission('withTableRecordOrder:noTraceRevoke'),
        ifRender: ifRenderRevoke,
      },
    ],
  },
})
const formInfo = ref({
  data: {},
  fieldList: [{ label: '撤回数量', value: 'invalidQty', type: 'slot' }],
  labelWidth: '180px',
})
const revokeDialogInfo = ref({
  title: '撤回',
  width: '30%',
  revokeVisible: false,
  btLoading: false,
  btList: [
    { label: '关闭', event: revokeHandleClose, show: true },
    { label: '确定', event: revokeHandleSave, show: true },
  ],
})
// 弹窗相关
const dialogInfo = reactive({
  title: '个体详情',
  width: '90%',
  btLoading: false,
  btList: [{ label: '关闭', event: handleClose, show: true }],
})
const printerInfo = reactive({
  visible: false,
  data: {},
})
const selectRow = ref('')

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('withTableRecordOrder:price'),
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('withTableRecordOrder:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
function ifRenderRevoke() {
  return props.info.status === 3
}
function ifRenderValue(row) {
  return props.pageStatus && row.codeType !== 1 && row.codeType !== 3
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  const search = filterInfo.keyword
  if (search) {
    tableInfo.data = tableInfo.copyData.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'qrCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'uniqueCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factorySubCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factoryMainCode') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.data = tableInfo.copyData
  }
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.invalidCalcQty / row.unitConvertCoefficient)
  } else {
    return row.invalidQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(row.invalidCalcQty / row.unitConvertCoefficient)
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.invalidCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row) {
  let largeUnitQty = parseInt(row.invalidCalcQty / row.unitConvertCoefficient)
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.invalidCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
}
function noTraceRevoke(row) {
  //无痕撤回
  if (row.codeType === 1 || row.codeType === 4) {
    formInfo.value.data = proxy.$fn.deepClone(row)
    formInfo.value.data.invalidCalcQty = proxy.$fn.deepClone(row.calcQty)
    formInfo.value.data.invalidQty = proxy.$fn.deepClone(row.qty)
    revokeDialogInfo.value.revokeVisible = true
  } else if (row.codeType === 2 || row.codeType === 3) {
    revokeSave(row)
  }
}
function revokeSave(row) {
  withTableRecordOrderRevokeDetail(row).then((res) => {
    if (res && res.success) {
      returnBack()
    }
  })
}
function revokeHandleSave() {
  let smallUnitQty = parseFloat(formInfo.value.data.smallUnitQty || 0)
  let unitConvertCoefficient = parseFloat(
    formInfo.value.data.unitConvertCoefficient || 1
  )
  let largeUnitQty = parseFloat(formInfo.value.data.largeUnitQty || 0)
  let calcQty = proxy.$fn.accAdd(
    proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
    smallUnitQty
  )
  let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
  formInfo.value.data.calcQty = calcQty
  formInfo.value.data.qty = qty
  if (calcQty <= 0) {
    proxy.$message({
      message: '请输入撤回数量',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  revokeSave(formInfo.value.data)
}
function returnBack() {
  shows.value = false
  emit('returnBack')
}
//撤回弹窗关闭
function revokeHandleClose() {
  //清空数据
  formInfo.value.data = {}
  revokeDialogInfo.value.revokeVisible = false
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function handleEvent(event, data) {
  switch (event) {
    case 'list':
      tableInfo.copyData = data
      break
  }
}
//打印单个二维码
function printSingleQrCode(row = undefined) {
  if (!row.qrCode) {
    proxy.$message({
      message: '没有生成二维码，不能打印',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let ids = [row.id]
  if (ids.length > 0) {
    withTableRecordOrderDetailPrintQrCodeVO(ids).then((resp) => {
      if (resp && resp.success) {
        printerInfo.visible = true
        printerInfo.data = resp.data
      }
    })
  }
}
function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}
function getCustomize() {
  let param = {
    tableKey:
      'withTableRecordOrderIndividualDetails-com.slip.spd.entity.vo.withtable.WithTableRecordOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      tableInfo.api = props.api
      getList()
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.scan-groups {
  display: flex !important;
  align-items: center;
}
</style>
